package org.jsoncrypto;

import java.security.SecureRandom;

import javax.crypto.SecretKey;

import org.json.JSONObject;
import org.jsoncrypto.util.Base64;

public class JweDIR extends JcLibJwe_SK {
	public JweDIR(JcLibEnc enc) throws JcBaseException {
		super(enc, JcBase.KW_ALG_DIR);
	}

	@Override
	String encrypt(byte[] contentBytes, SecretKey aKey) throws JcBaseException {
    return JcBase.encrypt(contentBytes, mEnc.mHeaderStr, aKey, new SecureRandom());
	}
	
	@Override
	byte[] decrypt(SecretKey key) throws JcBaseException {
		try {
			String encodedJwtHeaderSegment = mEnc.mEncodedJwtHeaderSegment;
			String encodedJwtKeySegment = mEnc.mEncodedJwtKeySegment;
			String encodedJwtIvSegment = mEnc.mEncodedJwtIvSegment;
			String encodedJwtCryptoSegment = mEnc.mEncodedJwtCryptoSegment;
			byte[] jwtIntegritySegmentBytes = Base64
					.decodeUrl(mEnc.mEncodedJwtIntegritySegment);
			JSONObject header = mEnc.mHeader;
			byte[] secretKeyBytes;
			secretKeyBytes = key.getEncoded();
			return JcBase.doDecrypt(encodedJwtHeaderSegment,
					encodedJwtKeySegment, encodedJwtCryptoSegment,
					jwtIntegritySegmentBytes, header, secretKeyBytes, encodedJwtIvSegment);
		} catch (Exception e) {
			throw new JcBaseException(e);
		}
	}

}
